import React, { Component } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from 'assets/logo.png'
import styles from './index.module.scss'
import { login } from 'api/login'
import { saveToken } from 'utils/storage'
export default class Login extends Component {
  onFinish = async (values) => {
    try {
      let params = {}
      params.mobile = values.mobile
      params.code = values.code
      const res = await login(params)
      saveToken(res.data.token)
      // localStorage.setItem('system-token', res.data.token)
      this.props.history.push('/')
      message.success('登录成功', 1.5)
    } catch (error) {
      if (error.response) {
        message.error(error.response.data.message, 1.5)
      } else {
        message.error('登录失败，请重新尝试', 1)
      }
      // console.dir(error)
    }
  }
  render() {
    return (
      <div className={styles.login}>
        <Card className='login-container'>
          <img className='login-logo' src={logo} alt='极客园' />
          <Form size='large' onFinish={this.onFinish} initialValues={{ mobile: '13911111111', code: '246810', agree: true }}>
            {/* label='mobile' 加上lable值和name值不相同的话，输入框拿不到值 */}
            <Form.Item
              name='mobile'
              rules={[
                { required: true, message: '手机号码不能为空!' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误' },
              ]}
            >
              <Input placeholder='请输入手机号码' />
            </Form.Item>
            <Form.Item
              name='code'
              rules={[
                { required: true, message: '验证码不能为空!' },
                { pattern: /^\d{6}$/, message: '验证码格式错误' },
              ]}
            >
              <Input placeholder='请输入验证码' />
            </Form.Item>
            <Form.Item
              valuePropName='checked'
              name='agree'
              rules={[
                {
                  validator: (_, value) => {
                    return value ? Promise.resolve() : Promise.reject('错误提示')
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>
            <Form.Item>
              <Button block type='primary' htmlType='submit'>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
